import { FC, useEffect, useRef } from "react";
import { forEach } from "lodash";
type Props = {
  width: number;
  height: number;
  roil: [number, number][][];
  callbackSource?: (v: any) => void
  source: string;
};

const getSizeRadio = (s: string, w: number, h: number) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = s;
    img.setAttribute("crossOrigin",'Anonymous')
    img.onload = () => {
      const wRadio = img.width / w;
      const hRadio = img.height / h;
      if (wRadio > hRadio) {
        resolve([wRadio, wRadio, img.width, img.height, img]);
      } else {
        resolve([hRadio, hRadio, img.width, img.height, img]);
      }
    };
  });
};

const RoilView: FC<Props> = ({ width, callbackSource, source, height, roil }) => {
  const elRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    void (async () => {
      if (!elRef.current) return;
      const [wRadio, hRadio, imgWidth, imgHeight, img] = await getSizeRadio(source, width, height);
      const ctx = elRef.current.getContext("2d");
      elRef.current.width = imgWidth;
      elRef.current.height = imgHeight;
      if (!ctx) return;
      ctx.clearRect(0, 0, width, height);
      ctx.drawImage(img,0, 0, imgWidth, imgHeight)
      ctx.strokeStyle = "red";
      ctx.lineWidth = 6
      forEach(roil, (group, gidx) => {
        ctx.beginPath();
        forEach(group, ([x, y], idx) => {
          if (idx === 0) {
            ctx.moveTo(x, y);
          } else {
            ctx.lineTo(x, y);
          }
        });
        ctx.closePath()
        ctx.stroke();
      });
      //
      // ctx.strokeStyle = '#000'
      // ctx.rect(0, 0, imgWidth / wRadio, imgHeight / hRadio)
      // ctx.stroke()

      callbackSource?.(elRef.current.toDataURL())
    })();
  }, [width, height, JSON.stringify(roil), source]);
  return (
    <canvas
      ref={elRef}
      className="fixed top-[5000px] left-[5000px]"
    />
  );
};

export default RoilView;
